package com.jhte.scheduleJob.base.util;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;

public class HttpClient {

    public static void main(String[] args) {
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("login_id", "rufus");
        jsonParam.put("password", "12p123$");
        jsonParam.put("device_id", "");
        jsonParam.put("token", "");
        jsonParam.put("moatoken", "aaa");
        //System.out.println(doImPost("/users/login", jsonParam));
    }


    public static JSONObject doPost(String url, JSONObject jsonParam) {
        SSLClient httpClient = null;
        HttpPost httpPost = null;
        JSONObject result = new JSONObject();

        String path = PropertiesUtils.getProperty("mm_path");
        try {
            httpClient = new SSLClient();
            httpPost = new HttpPost(path + url);
            StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");

            httpPost.setEntity(entity);

            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                JSONArray header = JSONArray.fromObject(response.getHeaders("token"));
                HttpEntity resEntity = response.getEntity();
                JSONObject body = new JSONObject();
                if (resEntity != null) {
                    body = JSONObject.fromObject(EntityUtils.toString(resEntity, "utf-8"));
                }
                result.put("header", header);
                result.put("body", body);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

}